package pers.vic.sso.common.util;

import com.fasterxml.jackson.core.type.TypeReference;
import pers.vic.boot.base.craw.CrawlConnect;
import pers.vic.boot.base.model.BaseResponse;
import pers.vic.boot.util.JsonUtil;
import pers.vic.sso.common.constant.Oauth2Constant;
import pers.vic.sso.common.enums.GrantTypeEnum;
import pers.vic.sso.common.model.RpcAccessToken;

import java.io.IOException;

/**
 * 描述:
 *      sso Oauth2 工具类
 * @author Vic.xu
 * @date 2021-11-03 11:50
 */
public class SsoOauth2Util {

    /**
     * 调用服务端刷新token接口
     * @param serverUrl
     * @param appId
     * @param refreshToken
     * @return
     */
    public static BaseResponse<RpcAccessToken> refreshToken(String serverUrl, String appId, String refreshToken) {
        CrawlConnect connect = SsoHttpUtil.connect(serverUrl + Oauth2Constant.REFRESH_TOKEN_URL);
        connect.data(Oauth2Constant.APP_ID, appId)
                .data(Oauth2Constant.REFRESH_TOKEN, refreshToken);
        return getRpcAccessTokenBaseResponse(connect);

    }


    /**
     *  通过code获取 accessToken
     * @param serverUrl
     * @param appId
     * @param appSecret
     * @param code
     * @return
     */
    public static BaseResponse<RpcAccessToken> getAccessToken(String serverUrl, String appId, String appSecret, String code) {
        CrawlConnect connect = SsoHttpUtil.connect(serverUrl + Oauth2Constant.ACCESS_TOKEN_URL);
        connect.data(Oauth2Constant.GRANT_TYPE, GrantTypeEnum.AUTHORIZATION_CODE.name())
                .data(Oauth2Constant.APP_ID, appId)
                .data(Oauth2Constant.APP_SECRET, appSecret)
                .data(Oauth2Constant.AUTH_CODE, code);
        return getRpcAccessTokenBaseResponse(connect);

    }

    private static BaseResponse<RpcAccessToken> getRpcAccessTokenBaseResponse(CrawlConnect connect) {
        try {
            String text = connect.postBodyText();
            BaseResponse<RpcAccessToken> response = JsonUtil.jsonToObject(text, new TypeReference<BaseResponse<RpcAccessToken>>() {
            });
            return response;
        } catch (IOException e) {
            e.printStackTrace();
            return BaseResponse.error("发生了一些错误：" + e.getMessage());
        }
    }

    public static void main(String[] args) {
        String serverUrl = "http://localhost:8887";
        String appId = "testAppId";
        String appSecret = "456";
        String code = "CODE-24f9d49e654c4b4cbf5049a93c2197cb";
        BaseResponse<RpcAccessToken> accessToken = getAccessToken(serverUrl, appId, appSecret, code);
        JsonUtil.printJson(accessToken);
    }

}
